package com.chen.pageProcessor;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import java.util.List;
import java.util.Properties;

public class EntranceProcessor implements PageProcessor {
    private final Site site = Site.me().setRetryTimes(5).setSleepTime(900);

    private final TypeProcessor typeProcessor;

    public EntranceProcessor(TypeProcessor typeProcessor , Properties properties) {
        this.typeProcessor = typeProcessor;
        getSite().setSleepTime(Integer.parseInt(properties.getProperty("sleeptime")));
    }


    @Override
    public void process(Page page) {
        if (page.getUrl().regex("allSort").match()) {
            List<String> all = page.getHtml().xpath("//div[@class=\"main-classify\"]/div[@class=\"list\"]/div[@class=\"category-items\"]/div/div/div[@class=\"mc\"]/div[@class=\"items\"]/dl/dd/a").all();
            for (String s : all) {
                if (s.contains("list.jd.com")) {
                    Html html = Html.create(s);
                    String title = html.xpath("//a/text()").get();
                    String url = html.xpath("//a/@href").get();
                    Request request = getRequest("https://www.jd.com/allSort.aspx", "https:" + url);
                    request.putExtra("type", title);
                    request.setPriority(-1);
                    page.addTargetRequest(request);
                }
            }
        } else if (page.getUrl().regex("list.jd.com").match()) {
            typeProcessor.process(page);
        }
    }

    @Override
    public Site getSite() {
        return this.site;
    }

    public Request getRequest(String referer, String targetUrl) {
        Request request = new Request(targetUrl);
        request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        request.addHeader("Accept-Encoding", "gzip, deflate, br");
        request.addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        request.addHeader("Connection", "keep-alive");
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0");
        request.addHeader("Host", "list.jd.com");
        request.addHeader("Pragma", "no-cache");
        request.addHeader("X-Requested-With", "XMLHttpRequest");
        request.addHeader("Referer", referer);
        request.setPriority(1);

        return request;
    }
}
